import { Button, Dialog } from "@material-tailwind/react";

import CustomHeader from '@/components/CustomHeader';
import axios from 'axios';

import Image from 'next/image';

import { useRouter } from 'next/router'

import { message, Spin } from 'antd';

import { postHttpQuestImg } from "@/utils/requestFn";
import { useEffect, useState } from "react";


import ValidateDialogCom from "./indexs/component/ValidateDialog";


export default function ButtonLoading() {





    const router = useRouter();
    // const { userId } = router.query; 24518444659

    const [userId, setUserId] = useState(router.query.userId || '');

    const [step, setStep] = useState(0);



    const [showDialog, setShowDialog] = useState(false)
    // const [verificationStatus, setVerificationStatus] = useState(false)



    const [iDCardImg, setIDCardImg] = useState({
        frontImg: '',
        backImg: '',
        handIDCard: '',
        videoUrl: ''
    })
    const [iDCardImgStatus, setIDCardImgStatus] = useState({
        frontImg: false,
        backImg: false,
        handIDCard: false,
        videoUrl: false
    })



    const __init = async () => {
        const formData = new FormData();
        formData.append('user_id', userId);
        const result = await postHttpQuestImg('/api/get_user_info', formData);
        if (result.data.back_image) {
            setIDCardImg({
                backImg: result.data.back_image.Valid === 0 ? '' : result.data.back_image.FileUrl,
                frontImg: result.data.front_image.Valid === 0 ? '' : result.data.front_image.FileUrl,
                handIDCard: result.data.hand_front_image.FileUrl,
                videoUrl: ''
            })
            // setStep(result.data.step)
        }
    }


    // 初始化
    useEffect(() => {
        if(router.query.userId){
            __init();
        }
    }, [router.query.userId])


    // 拿到正面id
    const frontIDCodeImg = async (val: { target: { files: any[]; }; }) => {

        setIDCardImgStatus({ ...iDCardImgStatus, frontImg: true })
        const formData = new FormData();
        formData.append('front_image', val.target.files[0]);
        formData.append('user_id', userId);


        const result = await postHttpQuestImg('/api/verify_idcard_front', formData)
        if (result.code == 0) {
            setIDCardImg({
                ...iDCardImg,
                frontImg: result.data.fileurl,
            })
        }
        setIDCardImgStatus({ ...iDCardImgStatus, frontImg: false })

    }


    // 拿到背面id
    const backIDCodeImg = async (val: { target: { files: any[]; }; }) => {
        setIDCardImgStatus({ ...iDCardImgStatus, backImg: true })
        const formData = new FormData();
        formData.append('back_image', val.target.files[0]);
        formData.append('user_id', userId);
        const result = await postHttpQuestImg('/api/verify_idcard_back', formData)
        if (result.code == 0) {
            setIDCardImg({
                ...iDCardImg,
                backImg: result.data.fileurl,
            })
        }
        setIDCardImgStatus({ ...iDCardImgStatus, backImg: false })
    }

    // 手持身份证
    const handIDCodeImg = async (val: { target: { files: any[]; }; }) => {
        setIDCardImgStatus({ ...iDCardImgStatus, handIDCard: true })
        const formData = new FormData();
        formData.append('hand_front_image', val.target.files[0]);
        formData.append('user_id', userId);
        formData.append('step', '1');
        const result = await postHttpQuestImg('/api/verify_hand_idcard_front', formData)
        if (result.code == 0) {
            setIDCardImg({
                ...iDCardImg,
                handIDCard: result.data.fileurl,
            })
        }
        setIDCardImgStatus({ ...iDCardImgStatus, handIDCard: false })
    }


    // 录像
    const videoUrlIDCodeImg = async () => {


        setShowDialog(true)
        // setIDCardImgStatus({ ...iDCardImgStatus, handIDCard: true })
        // const formData = new FormData();
        // formData.append('hand_front_image', val.target.files[0]);
        // formData.append('user_id', userId);
        // formData.append('step', '1');
        // const result = await postHttpQuestImg('/api/verify_hand_idcard_front', formData)
        // if (result.code == 0) {
        //     setIDCardImg({
        //         ...iDCardImg,
        //         handIDCard: result.data.fileurl,
        //     })
        // }
        // setIDCardImgStatus({ ...iDCardImgStatus, handIDCard: false })
    }


    const setVerificationStatusFn = (status: boolean) => {
        setIDCardImgStatus({ ...iDCardImgStatus, videoUrl: status })

    }


    // const stepNext = (val: number) => {
    //     if ((iDCardImg.backImg != '' && iDCardImg.frontImg != '')) {
    //         setStep(val);
    //     }
    // }


    const desList = [
        {
            des: '請使用證件原件並確保完整無遮擋，請勿使用掃描件或截圖'
        },
        {
            des: '確保光線均勻明亮，避免反光或模糊'
        },
        {
            des: '拍攝時請保持平穩，不要晃動'
        },
    ]

    const desList2 = [
        {
            des: '直接手持證件，不要使用支架或放置在桌面上拍攝'
        },
        {
            des: '確保相機或手機與證件保持水平'
        },
        {
            des: '我們重視您的隱私，上傳的照片將受到保護'
        },
    ]

    const desList3 = [
        {
            des: '屏幕將顯示一段文字，請大聲清晰地跟讀'
        },
        {
            des: '背景應簡單、乾淨，避免繁雜的背景干擾'
        },
        {
            des: '我们重视您的隐私保护，上传的视频将严格保密'
        },
    ]




    return (
        <div className="relative min-h-screen">
            <CustomHeader title='實人認證' />
            <div className={`w-full px-6 mt-4 ${step == 0 ? '' : 'hidden'}`}>
                <p className="text-center py-2 text-lg">請準備好您的身份證或護照或駕照</p>
                <div>
                    <div className="flex justify-center w-full">
                        <div className="px-3 ">
                            <Spin spinning={iDCardImgStatus.frontImg}>
                                <Image
                                    src={`${iDCardImg.frontImg ? iDCardImg.frontImg : '/images/img/take-photo-bg.png'}`}
                                    alt="Example"
                                    className={`flex rounded-xl ${iDCardImg.frontImg ? 'scale-[.93]' : ''}`}
                                    width={622}
                                    height={370}
                                />
                                <input type="file" accept="image/*" capture="environment" className="absolute left-0 top-0 w-full h-full opacity-0" onChange={frontIDCodeImg}></input>
                            </Spin>
                        </div>
                    </div>
                    <p className="text-center py-2">點擊拍摄证件正面</p>
                </div>
                <div>
                    <div className="flex justify-center w-full">
                        <div className="px-3 ">
                            <Spin spinning={iDCardImgStatus.backImg}>
                                <Image
                                    src={`${iDCardImg.backImg ? iDCardImg.backImg : '/images/img/take-photo-bg.png'}`}
                                    alt="Example"
                                    className={`flex rounded-xl ${iDCardImg.backImg ? 'scale-[.93]' : ''}`}
                                    width={622}
                                    height={370}
                                />
                                <input type="file" accept="image/*" capture="camera" className="absolute left-0 top-0 w-full h-full opacity-0" onChange={backIDCodeImg}></input>
                            </Spin>
                        </div>
                    </div>
                    <p className="text-center py-2">點擊拍摄证件正面</p>
                </div>

                {
                    desList.map((item, index) => {
                        return (
                            <div className="flex px-2 mt-2" key={index}>
                                <div className="py-1 px-2">
                                    <svg
                                        className={` !w-[16px] !h-[16px] "`}
                                        fill="none"
                                        height="16"
                                        viewBox="0 0 16 16"
                                        width="16"
                                        xmlns="http://www.w3.org/2000/svg"
                                    >
                                        <path
                                            d="M6.43367 9.92151L12.6563 3.69885L13.5756 4.61809L6.43367 11.76L1.9743 7.30063L2.89354 6.38139L6.43367 9.92151Z"
                                            fill="black"
                                            fillOpacity="0.9"
                                        />
                                    </svg>
                                </div>
                                <p>{item.des}</p>
                            </div>
                        )
                    })
                }
            </div>
            <div className={`w-full px-6 mt-4 ${step == 1 ? '' : 'hidden'}`}>
                <p className="text-center py-2 text-lg">拍攝手持證件照</p>
                <div>
                    <div className="flex justify-center w-full">
                        <div className="px-3 ">
                            <Spin spinning={iDCardImgStatus.handIDCard}>
                                <Image
                                    src={`${iDCardImg.handIDCard ? iDCardImg.handIDCard : '/images/img/take-photo-bg.png'}`}
                                    alt="Example"
                                    className={`flex rounded-xl ${iDCardImg.handIDCard ? 'scale-[.93]' : ''}`}
                                    width={622}
                                    height={370}
                                />
                                <input type="file" accept="image/*" capture="environment" className="absolute left-0 top-0 w-full h-full opacity-0" onChange={handIDCodeImg}></input>
                            </Spin>
                        </div>
                    </div>
                    <p className="text-center py-2">點擊拍攝手持證件照正面</p>
                </div>
                {
                    desList2.map((item, index) => {
                        return (
                            <div className="flex px-2 mt-2" key={index}>
                                <div className="py-1 px-2">
                                    <svg
                                        className={` !w-[16px] !h-[16px] "`}
                                        fill="none"
                                        height="16"
                                        viewBox="0 0 16 16"
                                        width="16"
                                        xmlns="http://www.w3.org/2000/svg"
                                    >
                                        <path
                                            d="M6.43367 9.92151L12.6563 3.69885L13.5756 4.61809L6.43367 11.76L1.9743 7.30063L2.89354 6.38139L6.43367 9.92151Z"
                                            fill="black"
                                            fillOpacity="0.9"
                                        />
                                    </svg>
                                </div>
                                <p>{item.des}</p>
                            </div>
                        )
                    })
                }
            </div>
            <div className={`w-full px-6 mt-4 ${step == 2 ? '' : 'hidden'}`}>
                <p className="text-center py-2 text-lg">錄製視頻</p>
                <div>
                    <div className="flex justify-center w-full">
                        <div className="px-3 ">
                            <Spin spinning={iDCardImgStatus.videoUrl}>
                                <Image
                                    src={`${iDCardImg.videoUrl ? iDCardImg.videoUrl : '/images/img/take-photo-bg.png'}`}
                                    alt="Example"
                                    className={`flex rounded-xl ${iDCardImg.videoUrl ? 'scale-[.93]' : ''}`}
                                    width={622}
                                    height={370}
                                />
                                <input type="file" accept="image/*" capture="environment" className="absolute left-0 top-0 w-full h-full opacity-0" onChange={videoUrlIDCodeImg}></input>
                            </Spin>
                        </div>
                    </div>
                    <p className="text-center py-2">點擊錄製視頻</p>
                </div>
                {
                    desList3.map((item, index) => {
                        return (
                            <div className="flex px-2 mt-2" key={index}>
                                <div className="py-1 px-2">
                                    <svg
                                        className={` !w-[16px] !h-[16px] "`}
                                        fill="none"
                                        height="16"
                                        viewBox="0 0 16 16"
                                        width="16"
                                        xmlns="http://www.w3.org/2000/svg"
                                    >
                                        <path
                                            d="M6.43367 9.92151L12.6563 3.69885L13.5756 4.61809L6.43367 11.76L1.9743 7.30063L2.89354 6.38139L6.43367 9.92151Z"
                                            fill="black"
                                            fillOpacity="0.9"
                                        />
                                    </svg>
                                </div>
                                <p>{item.des}</p>
                            </div>
                        )
                    })
                }
            </div>
            <div className="h-28"></div>
            <div className=" fixed z-50 bottom-5  left-0 w-full px-6">
                <div className={`${step == 0 ? '' : 'hidden'}`}>
                    <Button variant="filled" onClick={() => {
                        if ((iDCardImg.backImg != '' && iDCardImg.frontImg != '')) {
                            setStep(1)
                        }
                    }} loading={iDCardImgStatus.backImg || iDCardImgStatus.frontImg} ripple={(iDCardImg.backImg != '' && iDCardImg.frontImg != '')} className={`${(iDCardImg.backImg != '' && iDCardImg.frontImg != '') ? 'bg-mainColor text-white' : 'bg-btnColor text-mainTextColor'}   p-3 text-center  rounded-xl w-full text-sm flex justify-center `} placeholder={'undefined'} onPointerEnterCapture={undefined} onPointerLeaveCapture={undefined}>
                        下一步
                    </Button>
                </div>
                <div className={`${step == 1 ? '' : 'hidden'}`}>
                    <Button variant="filled" onClick={() => {
                        if (iDCardImg.handIDCard != '') {
                            setStep(2)
                        }
                    }} className={`${iDCardImg.handIDCard ? 'bg-mainColor text-white' : 'bg-btnColor text-mainTextColor'}  p-3 text-center  rounded-xl w-full text-sm `} placeholder={'undefined'} onPointerEnterCapture={undefined} onPointerLeaveCapture={undefined}>
                        下一步
                    </Button>
                </div>
                <div className={`${step == 2 ? '' : 'hidden'}`}>
                    <Button variant="filled" loading={iDCardImgStatus.videoUrl} onClick={() => videoUrlIDCodeImg()} className={`${iDCardImg.handIDCard ? 'bg-mainColor text-white' : 'bg-btnColor text-mainTextColor'}  p-3 text-center  rounded-xl w-full text-sm text-center `} placeholder={'undefined'} onPointerEnterCapture={undefined} onPointerLeaveCapture={undefined}>
                        {(!iDCardImgStatus.videoUrl && iDCardImg.videoUrl != '') ? '完成' : '开始验证'}
                    </Button>
                </div>
            </div>


            <ValidateDialogCom isModalVisible={showDialog} verificationStatus={setVerificationStatusFn} setIsModalVisible={setShowDialog} userId={userId}></ValidateDialogCom>

        </div>
    );
}
